package com.evan.uyclub.AppStore;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;

import com.evan.uyclub.Other.BrowserActivity;
import com.evan.uyclub.Other.Utlis;
import com.evan.uyclub.Other.VPNActivity;
import com.evan.uyclub.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sdsmdg.tastytoast.TastyToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import net.steamcrafted.loadtoast.LoadToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class ActivityApp extends AppCompatActivity {
    private static URL url;
    private static HttpURLConnection con;
    private static int state = -1;
    private List<ListReturn> listReturns = new LinkedList<>();
    private ListnAdapter listAdapter;
    private TextView title;
    private String urls, token, lid;
    private BottomSheetDialog dialog;
    private CardView App_Dow;
    private ListReturn dows;
    private TextView App_Dow_Text;
    private String apkPath;
    private ImageView imgs;
    private View dowurl;
    private LoadToast loadToast;
    private SweetAlertDialog pDialog;
    private ListView main_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app);
        /*TastyToast.makeText(getApplicationContext(),"由于应用安全及平台审核问题应用专区已被关闭",TastyToast.LENGTH_LONG,TastyToast.ERROR);*/
        main_list = findViewById(R.id.app_list);
        imgs = findViewById(R.id.imgs);
        title = findViewById(R.id.titles);
        Intent intent = getIntent();
        String titles = intent.getStringExtra("title");
        token = intent.getStringExtra("token");
        title.setText(titles);
        urls = intent.getStringExtra("url");
        lid = intent.getStringExtra("lid");
        Log.e("URLS", urls);
        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> {
            onBackPressed(); // 退出页面
        });
        //vpn检测
        VPNActivity vpnActivity = new VPNActivity(this);
        SmartRefreshLayout app_smarts = (SmartRefreshLayout) findViewById(R.id.app_smarts);
        app_smarts.setEnableLoadMore(false);
        app_smarts.setEnablePureScrollMode(false);
        app_smarts.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {
                Begin();
                refreshlayout.finishRefresh();
            }
        });
        Dialng();
        Dialogs();
        Begin();
    }

    private void Begin() {
        //初始化
        Adapter_list();
        //数据请求
        Data_list();
        //倒计时取消
        Dialng();
        Dialogs();
    }

    private void Dialog_off() {
        loadToast.success();
        main_list.setVisibility(View.VISIBLE);
        imgs.setVisibility(View.GONE);
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(main_list, "alpha", 0f, 1f);
        objectAnimator.setDuration(1000);
        objectAnimator.start();
    }

    private void Dialog_on() {
        TastyToast.makeText(getApplicationContext(), "请检查网络哦!", TastyToast.LENGTH_LONG, TastyToast.ERROR);
        loadToast.error();
        main_list.setVisibility(View.GONE);
        imgs.setVisibility(View.VISIBLE);
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imgs, "alpha", 0f, 1f);
        objectAnimator.setDuration(1000);
        objectAnimator.start();

    }

    private void Dialogs() {
        if (isNetworkAvailable(ActivityApp.this)) {
            new Handler().postDelayed(this::Dialog_off, 1400);
        } else {
            new Handler().postDelayed(this::Dialog_on, 1400);
        }
        /*dialog.dismiss();
        pDialog.dismiss();**/

    }

    private void Adapter_list() {
        listAdapter = new ListnAdapter(ActivityApp.this, R.layout.app_item, listReturns);
        /*AppAdapter listAdapter = new AppAdapter(listReturns);*/
        main_list.setAdapter(listAdapter);

        main_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
                dows = listReturns.get(position);
                App_Dow_Text = view.findViewById(R.id.App_DowText);
                //App_Dow_Text.setText("下载");
                App_Dow = (CardView) view.findViewById(R.id.App_Dow);
                /*下载地址获取*/
                TextView textView = view.findViewById(R.id.item_download_url);
                String id = textView.getText().toString().trim();
                EasyHttp.get("https://uyclouds.com/uyapi/lanzou_download.php")
                        .params("keeper", "3487297072")
                        .params("api", "488588")
                        .params("user", "123456")
                        .params("pass", "123456")
                        .params("id", lid)
                        .params("Lid", dows.getDownloadUrl())
                        .params("accesstoken", token)
                        .execute(new SimpleCallBack<String>() {
                            @Override
                            public void onError(ApiException e) {
                                TastyToast.makeText(ActivityApp.this, "下载失败，请重试", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                            }

                            @Override
                            public void onSuccess(String s) {
                                try {
                                    JSONObject jsonObject = new JSONObject(s);
                                    if (!jsonObject.getString("code").equals("true")) {
                                        TastyToast.makeText(ActivityApp.this, jsonObject.getString("msg"), TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                                        return;
                                    }
                                   /* if (jsonObject.getString("msg").contains("你不是会员用户")) {
                                        TastyToast.makeText(ActivityApp.this, "暂无法下载，请换个应用", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                                        return;
                                    }*/
                                    /*Download(jsonObject.getString("name"), jsonObject.getString("downurl"));*/
                                    Intent intent3 = new Intent();
                                    intent3.putExtra("网址", jsonObject.getString("downurl"));
                                    intent3.setClass(ActivityApp.this, BrowserActivity.class);
                                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(jsonObject.getString("downurl")));
                                    startActivity(intent);
                                    overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                /*App_Dow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (App_Dow_Text.getText().toString().equals("可下载")) {
                            App_Dow_Text.setText("下载ing");
                            Download(); // 下载APK
                        } else if (App_Dow_Text.getText().toString().equals("安装")) {
                            installApk(); // 安装APK
                        } else if (App_Dow_Text.getText().toString().equals("失败")) {
                            TastyToast.makeText(ActivityApp.this, "数据异常，请改天再试", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                        } else {
                            TastyToast.makeText(ActivityApp.this, "正在下载中...", TastyToast.LENGTH_SHORT, TastyToast.WARNING).show();
                        }
                    }
                });*/
            }
        });
    
        /*StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        main_list.setLayoutManager(layoutManager);
        ListAdapter adapter=new ListnAdapter(listReturns);
        main_list.setAdapter((RecyclerView.Adapter) adapter);*/

    }


    //下载
    public void Download(String name, String url) {
        String app_url = dows.getDownloadUrl();
        String app_name = dows.getNameApp();
        EasyHttp.downLoad(url).saveName(name)//不设置默认名字是时间戳生成的
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        int progress = (int) (bytesRead * 100 / contentLength);
                        App_Dow_Text.setText(progress + "%");
                        if (done) {//下载完成
                            App_Dow_Text.setText("安装");
                        }
                    }

                    @Override
                    public void onStart() {
                        //开始下载
                        App_Dow_Text.setText("下载中");
                    }

                    @Override
                    public void onComplete(String path) {
                        //下载完成，path：下载文件保存的完整路径
                        App_Dow_Text.setText("安装");
                        apkPath = path;
                    }

                    @SuppressLint("ResourceAsColor")
                    @Override
                    public void onError(ApiException e) {
                        //下载失败
                        App_Dow_Text.setText("失败");
                    }
                });

    }

    /*
     * 下载到本地后执行安装
     */
    @SuppressLint("ObsoleteSdkInt")
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(apkPath);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    private void Data_list() {
        listReturns.clear();
        if (!Utlis.isVPNConnected(this)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    EasyHttp.get(urls)
                            .execute(new SimpleCallBack<String>() {
                                @Override
                                public void onError(ApiException e) {

                                }

                                @Override
                                public void onSuccess(String data) {
                                    try {
                                        Log.e("ActivityApp", "onSuccess: " + data);
                                        JSONObject object = new JSONObject(data);
                                        JSONArray jsonArray = object.getJSONArray("listdata");
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                                            Log.e("data" + i, jsonObject.toString());
                                            ListReturn listReturn = new ListReturn(jsonObject.getString("ico"), jsonObject.getString("name"), jsonObject.getString("size"), jsonObject.getString("Lid"), jsonObject.getString("type"), jsonObject.getString("type"), jsonObject.getString("type"));
                                            listReturns.add(listReturn);
                                        }
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                listAdapter.notifyDataSetChanged();
                                            }
                                        });
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }
            }).start();
        }
    }

    public void Dialng() {
        loadToast = new LoadToast(ActivityApp.this);
        loadToast.setText("加载Ing...");
        loadToast.setProgressColor(R.color.green_active);
        loadToast.setBorderColor(R.color.fbutton_color_emerald);
        loadToast.setTranslationY(105);
        loadToast.show();
    }

    @Override
    public void onBackPressed() { // 退出页面的效果
        finish();
    }


    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}